import axios from "axios";
import {ElMessage} from 'element-plus'
import type {BaseResponse} from "@/api/baseResponse";
import {useCounterStore} from "@/stores/counter";
import router from "@/router";

const http = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 10000
});

http.interceptors.request.use(request => {
    request.headers['Access-Token'] = useCounterStore().getToken();
    return request;
});

http.interceptors.response.use(response => {
    const data: BaseResponse<any> = response.data;
    if (data.code == 20000) {
        return response;
    } else if (data.code == 40000) {
        router.push({
            path: '/login'
        })
        ElMessage.error(data.msg)
        return Promise.reject(data.msg);
    } else {
        ElMessage.error(data.msg)
        return Promise.reject(data.msg);
    }
});

export default http